package com.kyzh.core.pager.weal.accountbuy

import android.annotation.SuppressLint
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import android.widget.ImageView
import androidx.activity.viewModels
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.observe
import androidx.recyclerview.widget.GridLayoutManager
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.entity.node.BaseNode
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.google.gson.Gson
import com.gushenge.atools.util.setHeight
import com.gushenge.core.base.activity.BaseActivity
import com.gushenge.core.beans.Small
import com.gushenge.core.beans.TradeConfig
import com.gushenge.core.dao.GlobalKeys
import com.gushenge.core.impls.GameImpl
import com.gushenge.core.listeners.ResultListener
import com.gushenge.core.requests.AppRequest
import com.huantansheng.easyphotos.EasyPhotos
import com.huantansheng.easyphotos.callback.SelectCallback
import com.huantansheng.easyphotos.models.album.entity.Photo
import com.kyzh.core.R
import com.kyzh.core.uis.SuperView
import com.kyzh.core.uis.alert
import com.kyzh.core.uis.alert1
import com.kyzh.core.utils.*
import com.kyzh.core.viewmodel.SmallToSellVM
import kotlinx.android.synthetic.main.activity_smalltosell.*
import kotlinx.android.synthetic.main.titlebar.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import org.jetbrains.anko.toast
import com.gushenge.core.toast
class SmallToSellActivity : BaseActivity() {
    private var trade: TradeConfig?=null
    private val vm: SmallToSellVM by viewModels()
    private var images = arrayListOf<Uri>()
    val context = this@SmallToSellActivity
    private val adapter = ImageAdapter(R.layout.deal_images_item, images)
    val imageArrays = arrayListOf<String>()
    var loading: AlertDialog? = null

    var gPositiong = 0
    companion object {
        const val SUCCESS = 1
        const val ERROR = 2
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_smalltosell)
        initView()
        initData()
        getFeiLv()
    }

    //获取费率
    private fun getFeiLv(){
        GameImpl.getTradeConfig {
            trade=this
        }
    }

    private fun initData() {

        val small = intent.getSerializableExtra(GlobalKeys.KEY) as Small
        vm.setSmall(small)
        svGame.setOnClickListener {
            shouListWindow(small.data as ArrayList<BaseNode>) {
                gPositiong = this
                svGame.setEndText((small.data[this] as Small.Data).gname)
                svSmall.setEndText((small.data[this] as Small.Data).role_name)
            }
        }
        /*图片列表*/
        vm.getImages().observe(context) {
            images.clear()
            images.addAll(it)
            if (it.size < 6) {
                images.add(drawableToUri(R.drawable.deal_add))
            }
            rvImages.setHeight( dip(if (images.size > 3) 205 else 110))
            adapter.notifyDataSetChanged()

        }
    }

    private fun initView() {
        svPrice2.setEnable(false)
        close.setOnClickListener { finish() }
        tvTitle.text = "我要卖号"
        alert1("我要卖号", "", "立即出售", "放弃出售") {
            error { -> finish() }
        }.setCancelable(false)
        rvImages.layoutManager = object : GridLayoutManager(context, 3) {
            override fun canScrollHorizontally(): Boolean {
                return false
            }

            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        rvImages.adapter = adapter
        val add = drawableToUri(R.drawable.deal_add)
        adapter.setOnItemClickListener { adapter, view, position ->
            /*
            * 图片预览点击事件
            * 如果点击的position是最后一位的话
            * 说明有两种可能
            * 选择图片或者预览图片 */
            if (position == images.size - 1) {
                if (images[position] == add) {
                    /*选择图片,个数为 6-image.size+1*/
                    images.remove(add)
                    chooseImage(6 - images.size)
                } else {
                    reviewImagesFromUri(images, position)
                }
            } else {
                reviewImagesFromUri(images, position)
            }
        }
        adapter.setOnItemLongClickListener { adapter, view, position ->
            if (images.isNotEmpty()){
                val image = images[position]
                vm.deleteImage(image)
                true
            }else{
                false
            }
        }

        btSell.setOnClickListener {
            if (images.isNullOrEmpty()) {
                toast(getString(R.string.pleaseSelectImage))
            } else {
                if (images.size ==1 && images.contains(add)){
                    toast(getString(R.string.pleaseSelectImage))
                }else{
                    loading = loading()
                    getString(R.string.pleaseWaitToUploadingImage).toast()
                    imageArrays.clear()
                    GlobalScope.launch {
                        repeat(images.size-1){
                            Log.e( "initView: ",it.toString() )
                            AppRequest.uploadImage(this@SmallToSellActivity,images[it]){
                                Log.e("initView: ",this )
                                imageArrays.add(this)
                                if (imageArrays.size == images.size-1){
                                    val imagetoJson = Gson().toJson(imageArrays)
                                    val message = Message()
                                    message.what = SUCCESS
                                    message.obj = imagetoJson
                                    handler.sendMessage(message)
                                    cancel()
                                }
                            }
                        }

                    }
                }
            }
        }
        svSystem.setOnClickListener {
            alert(getString(R.string.pleaseSelectSystem), message = "", yesButtonText = "Android", noButtonText = "iOS",
                    {
                        svSystem.setEndText("Android")
                    },
                    {
                        svSystem.setEndText("iOS")
                    }
            )
        }
        svPrice.setOnTextChangeListener(object : SuperView.textChangeListener {
            override fun onchange(string: String) {
                val money = if (string.isNotEmpty()) string.toInt() else 0
                var getMoney=0.00
                if(trade!=null){
                    getMoney = money - (if (money * trade!!.fee > trade!!.money) (money * trade!!.fee).toDouble() else trade?.money)!!
                }

                 if (getMoney < 0) {
                    svPrice2.setEndText("")
                    svPrice2.setEndHintText(  "售价不能低于${trade?.money}")
//                    getString(R.string.priceNotLessThanFive)
                } else {
                    svPrice2.setEndText("${getMoney}${getString(R.string.yuan)}")
                }

            }
        })
    }

    private fun chooseImage(i: Int) {
        EasyPhotos.createAlbum(context, false,false, GlideEngine)
                .setCount(i)
                .setFileProviderAuthority("/").start(object : SelectCallback() {
                    override fun onResult(photos: ArrayList<Photo>?, isOriginal: Boolean) {
                        photos?.let {
                            for (i in it) {
                                vm.addImage(i.uri)
                            }
                        }
                    }

                override fun onCancel() {
                }

            })
    }


    private inner class ImageAdapter(layout: Int, beans: ArrayList<Uri>) : BaseQuickAdapter<Uri, BaseViewHolder>(layout, beans) {

        override fun convert(helper: BaseViewHolder, item: Uri) {
            val imageView: ImageView = helper.getView(R.id.imageView)
            item?.let { image ->
                Glide.with(context).load(image).into(imageView)
            }
        }
    }


    private val handler = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                SUCCESS -> {
                    val imagetoJson = msg.obj as String
                    vm.post(svTitle.getContent(),gPositiong,  etDesc.text.toString(), svServer.getContent(), svPassword.getContent(), imagetoJson, svPrice.getContent(), svSystem.getContent(), object : ResultListener {
                        override fun success() {
                            loading?.dismiss()
                            finish()

                        }

                        override fun error() {
                            loading?.dismiss()
                            toast(getString(R.string.noBindPhone))

                        }

                        override fun error(error: String) {
                            loading?.dismiss()
                            toast(error)

                        }
                    })
                }
            }
        }
    }


}
